<template>
  <selector type="radio" v-model="productLineCode" :data="products" fields="code,name"
            :enumCount="2" @change="productLine_change"
            chk="*"></selector>
</template>

<script type="text/ecmascript-6">


export default {
  data: function () {
    return {
      productLineCode:"",
      products: []
    }
  },
  prop:{
    value:{type:String,default:""}
  },
  mounted() {
    this.$loadData("productLineCode")
    this.db_products = [];
    this.$http.post("/dev/product-line/list").then(res => {
      this.db_products = res.data.data;


      this.sortWithLastProjectCodes(this.productLineCode)
    })
  },
  methods: {
    productLine_change(v, m, p) {
      if (p.cause == "change") {


        this.$saveData("productLineCode")

        this.sortWithLastProjectCodes(this.productLineCode)
      }

      this.$emit("input",v);
      this.$emit("change",v,m,p);
    },
    sortWithLastProjectCodes(code) {
      var last = localStorage.getJson("last-product-lines",[]);
      last = last.filter(it => it).distinct().slice(0, 24);
      if (code) {
        last.removeItem(code);
        last.insertAt(0, code)
        last = last.slice(0, 24)
        localStorage.setJson("last-product-lines", last)
      }
      this.products = this.db_products.sort((a, b) => {
        var aIndex = last.indexOf(a.code),
            bIndex = last.indexOf(b.code);
        if (aIndex < 0) return 1;
        if (bIndex < 0) return -1;
        return aIndex - bIndex;
      });
    }
  }
}
</script>